package com.molichuxing.services.infrastructure.service.impl;

import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.PushPayload;
import com.molichuxing.services.infrastructure.dto.request.create.NotifyPushCreateDto;
import com.molichuxing.services.infrastructure.service.NotifyPushService;
import com.molichuxing.services.util.JpushUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Author: renzhengyu
 * @Description:
 * @Date: Created in 10:59 2019/10/9
 * @Modified By:
 **/
@Service("notifyPushService")
public class NotifyPushServiceImpl implements NotifyPushService {
    private static final Logger logger = LoggerFactory.getLogger(NotifyPushServiceImpl.class);

    @Value("${jpush.appkey}")
    private String JPUSH_APPKEY;
    @Value("${jpush.master_secret}")
    private String JPUSH_MASTER_SECRET;
    @Value("${jpush.apns_production}")
    private Boolean JPUSH_APNS_PRODUCTION;

    private JPushClient jPushClient;

    /**
     * 推送消息
     *
     * @param createDto
     * @return
     * @throws Exception
     */
    @Override
    public boolean notifyPushByAlias(NotifyPushCreateDto createDto) throws Exception {
        return jPushByAlias(createDto);
    }


    /**
     * 极光推送(推送给设备标识参数的用户)
     *
     * @param createDto
     * @return
     * @throws Exception
     */
    private boolean jPushByAlias(NotifyPushCreateDto createDto) throws Exception {
        boolean result = false;
        if (jPushClient == null) {
            jPushClient = new JPushClient(JPUSH_MASTER_SECRET, JPUSH_APPKEY);
        }
        PushResult pushResult = null;
        try {
            PushPayload pushPayload = JpushUtils.buildPushObjectByAndroidAndIos(createDto, JPUSH_APNS_PRODUCTION);
            logger.info("极光推送请求数据" + pushPayload);
            pushResult = jPushClient.sendPush(pushPayload);
            logger.info("极光推送返回数据" + pushResult);
            if (pushResult.getResponseCode() == 200) {
                result = true;
            } else {
                logger.error("极光推送失败：" + pushResult.error);
            }

        } catch (Exception e) {
            logger.error("极光推送异常:", e);
        }

        return result;
    }
}
